import { ref } from "vue"
import type { TableInstance } from 'element-plus'
import { type FormInstance, ElMessage, ElMessageBox } from "element-plus"
import { useRoute, useRouter } from 'vue-router';

const useForm = (props: any)=> {
  const {formType, emit, backFun} = props
  const route = useRoute();
  const router = useRouter();
  const id = route.query.id;
  const loading = ref<boolean>(false)

  const back = ()=> {
    if(!backFun) {
      router.go(-1)
    } else {
      backFun()
    }
  }

  const handleSubmit = async(api: any, formEl:any,  formData: any, gmRef:any = null) => {
    await formEl.validate((valid: any) => {
      if (!valid) {
        return
      }
      if(formType == 'page') {
        loading.value = true
      } else {
        gmRef.setLoading(true)
      }
      api(formData).then((res: any)=>{
        ElMessage({
          message: '操作成功',
          type: 'success',
        })

        if(formType == 'page') {
          setTimeout(()=>{
            loading.value = false
            back()
          },2000)
        } else {
          gmRef.setLoading(false)
          emit('success')
        }

      }).catch(()=>{
        if(formType == 'page') {
          loading.value = false
        } else {
          gmRef.setLoading(false)
        }
      })
    })
  }

  return {
    handleSubmit,
    route,
    router,
    loading,
    id,
    back
  }
}

export default useForm
